
/*
 * Projet Implementation Reseau
 * Groupe:
 *	- Bertrand PROUHET
 * 	- Arthur HALET
 *	- Renaud HUMBLOT
 *	- Vlad MARIN
 */


#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <time.h>
 #include <sys/select.h>



// Autres constantes.
#define MAX_MSG 80
#define SERVER_PORT 1500

#define MAX_CONNEXIONS 5


#define TIMEOUT 1
#define NBRETRY 3


// Enumeration des etats possible d'un socket.
enum EtatTcp {
	CLOSE, 
	SYNSENT,
	SYNRECEIVED,
	LISTEN,
	ESTABLISHED,
	CLOSING,
	FIN_WAIT_1,
	FIN_WAIT_2,
	TIME_WAIT,
	CLOSE_WAIT,
	LAST_ACK
};



// Structure dediee a une connexion.
struct connexion {
	int 	etat;
	char 	window[1000];
	// rajouter SEQ et ACK
}; 



// Structure d'un packet TCP.
struct tcp_packet {
	int 			ID_emmeteur;
	unsigned short 	port_source;
	unsigned short 	port_destination;
	unsigned long	numero_sequance;
	unsigned long	numero_ack;
	unsigned short 	window;
	unsigned short 	crc;
	char			syn;
	char			fin;
	char			ack;
	char			rst;
	char			data[1000];
};



// Structure definissant un SocketTCP.
struct SocketTCP {
	int 				descripteur;
	socklen_t 			new_addr_len;
	struct sockaddr_in* 	new_addr;
	// Utiliser struct connexion
};

struct SocketTCP * getSocketTcpFromFd(int fd);
struct 	SocketTCP *creatSocketTCP();

void 	initialiserTCPPacket(struct tcp_packet* packet);

int 	f_accept(int sockfd, struct sockaddr* addr, socklen_t *addrlen);

int 	f_connect(int sockfd, struct sockaddr *addr, socklen_t addrlen );

int 	f_listen(int sockfd, int backlog);

int 	f_close(struct SocketTCP* socket);

ssize_t f_read(int fd, void *buf, size_t count); 

ssize_t f_write(int fd, const void *buf, size_t count);

int setISNTcpPacket(struct tcp_packet *sent_packet);

int timeoutSocketTcp(int sock, fd_set *readfd, fd_set *writefd);

int compareFlag(char * flag, struct tcp_packet *sent_packet);


// put flag inside tcp_packet format 1 and 0 (syn,ack,fin,rst)
int setFlag(char *flag, struct tcp_packet *sent_packet);

int estClientExistant(int ID, int* tab_ID);

int getIndiceClientExistant(int ID, int* tab_ID);
